public class RoundRobin extends Scheduler{
	int time_quantum = 5;
	public void run(){
		check_new();
		while(!queue.isEmpty() || !processes.isEmpty()){
			if(!queue.isEmpty()){
                queue.get(0).wait_time += time - queue.get(0).last_access;
                if(queue.get(0).last_access == 0)
					System.out.println("[Time: " + time + "ms][Process "  + queue.get(0).id + "|Burst Time: " + queue.get(0).burst + "ms|Wait time: " + queue.get(0).wait_time + "ms] is accessing the CPU for the first time");
				else
					System.out.println("[Time: " + time + "ms][Process "  + queue.get(0).id + "|Remaining Burst: " + queue.get(0).burst + "ms|Wait time: " + queue.get(0).wait_time + "ms] is accessing the CPU");
                while (queue.get(0).burst > 0){
                	queue.get(0).burst--;
                	queue.get(0).running_time++;
                    time++;
                    if(queue.get(0).running_time % time_quantum == 0 && queue.size() > 1)
                        break;
                    check_new();
                }
                context_switch();
			}
			else{
				time++;
                check_new();
			}
		}
		print_stats();
	}
	public void check_new() {
		while (!processes.isEmpty() && processes.get(0).arrival <= time) {
			queue.add(processes.get(0));
			System.out.println("[Time: " + time + "ms][Process " + processes.get(0).id + "|Burst Time: " + processes.get(0).burst + "ms] added to queue");
			processes.remove(0);
        }
	}
	public void context_switch(){
		Process p = queue.remove(0);
		if (p.burst <= 0){
			turnaround_times.add(time - p.arrival);
        	wait_times.add(p.wait_time);
        	System.out.println("[Time: " + time + "ms][Context Switch][Process " + p.id + "|Wait Time: " + p.wait_time + "ms|Turnaround Time " + (time - p.arrival) + "ms] has been terminated");
		}
		else{
			p.last_access = time;
			queue.add(p);
			System.out.println("[Time: " + time + "ms][Context Switch][Process " + p.id + "|Remaining Burst: " + p.burst + "ms] swapped out for [Process " + queue.get(0).id + "|Remaining Burst: " + queue.get(0).burst + "ms|Wait Time: " + queue.get(0).wait_time + "ms]");	
		}
		time += 3;
		context_switch_time += 3;
		context_switch_count++;
	}
}
